<template>
  <div style="height: 100%; padding: 10px; background: #eee">
    <n-card size="small">
      <n-space>
        <n-input
          v-model:value="searchName"
          size="small"
          placeholder="表名"
          style="width: 200px" />
        <n-button type="primary" size="small" @click="handleGenerateCode">
          <template #icon>
            <n-icon> <Code20Filled /> </n-icon>
          </template>
          生成代码
        </n-button>
      </n-space>
    </n-card>
    <n-card size="small" style="margin-top: 10px">
      <n-data-table
        v-model:checked-row-keys="selectedKeys"
        :row-key="(row) => row.tableName"
        :data="tablesData"
        :loading
        :columns
        striped
        size="small"
        :pagination="{
          pageSize: 10,
          itemCount: tablesData.length,
        }" />
    </n-card>
  </div>
</template>

<script lang="tsx" setup>
import { getTables } from "@/api";
import { DataTableColumns } from "naive-ui";
import { Code20Filled } from "@vicons/fluent";
import GenForm from "./GenForm.vue";

const columns: DataTableColumns = [
  { type: "selection" },
  { title: "序号", key: "no", width: "50px" },
  { title: "表名", key: "tableName" },
  { title: "表注释", key: "tableComment" },
];

const searchName = ref("");
const loading = ref(false);
const tables = ref<TableInfo[]>([]);
const selectedKeys = ref<string[]>([]);
let menuOption: MenuOption;

const tablesData = computed(() => {
  return tables.value
    .filter((item) => item.tableName.includes(searchName.value))
    .map((item, idx) => ({ ...item, no: idx + 1 }));
});

const handleTableSelect = async (option: MenuOption) => {
  menuOption = option;
  loading.value = true;
  try {
    const { data } = await getTables(option.target.info, option.label!);
    tables.value = data;
    selectedKeys.value = [];
  } finally {
    loading.value = false;
  }
};

const handleGenerateCode = () => {
  if (loading.value) return window.$message?.warning("请等待表信息加载完毕");
  if (!selectedKeys.value.length)
    return window.$message?.warning("请选择要生成的表");

  const formRef = ref<InstanceType<typeof GenForm>>();
  window.$dialog?.create({
    title: "代码信息",
    titleStyle: "font-size: 16px",
    contentStyle: "padding-top: 20px",
    content: () => <GenForm ref={formRef} />,
    positiveText: "确认",
    negativeText: "算了",
    onPositiveClick: async () => {
      const rows = tables.value.filter((item) =>
        selectedKeys.value.includes(item.tableName)
      );
      await formRef.value!.handleGenCode(menuOption, rows);
    },
  });
};

defineExpose({ handleTableSelect });
</script>
